//
//  YXYCustomTextView.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/7/3.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit

class YXYCustomTextView: UITextView {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var placeHolder: String? {
        didSet {
            placeLabel.text = placeHolder
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeLabel.font = font
        }
    }
    // MARK: - 添加子控件
    private func setUpUI () {
        addSubview(placeLabel)
        placeLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self).offset(7)
            make.leading.equalTo(self).offset(5)
            make.width.equalTo(self).offset(-10)
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        // 通过代理去监听textView是否有值，在这里不好使
        //self.delegate = self
    }
    
    /// 懒加载控件
    lazy var placeLabel: UILabel = {
        let lab = UILabel()
        lab.textColor = UIColor.grayColor()
        lab.numberOfLines = 0
        lab.sizeToFit()
        return lab
    }()
    
    // 监听textView的内容改变
    @objc private func textViewChange () {
        placeLabel.hidden = self.hasText()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
//    @objc private func textViewChange (noti: NSNotification) {
//        if let textView = noti.object as? UITextView {
//            if textView.hasText() {
//                placeLabel.hidden = true
//            }else {
//                placeLabel.hidden = false
//            }
//        }
//    }
    
    // OC 的字符串(NSString)才可以进行绘制
    
//    override func drawRect(rect: CGRect) {
//        placeHolder?.drawAtPoint(CGPoint(x: 5, y: 8), withAttributes: [NSFontAttributeName: font!])
//    }
    
}

//extension YXYCustomTextView: UITextViewDelegate {
//    func textViewDidChange(textView: UITextView) {
//        placeLabel.hidden = self.hasText()
//    }
//}

